package com.fuang.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Fuang on 2017-12-24.
 */
@Component
public class AccessFilter extends ZuulFilter {

    private static final Logger LOG = LoggerFactory.getLogger(AccessFilter.class);

    /**
     * to classify a filter by type. Standard types in Zuul are "pre" for pre-routing filtering,
     * "route" for routing to an origin, "post" for post-routing filters, "error" for error handling.
     * We also support a "static" type for static responses see  StaticResponseFilter.
     * Any filterType made be created or added and run by calling FilterProcessor.runFilters(type)
     *
     * @return A String representing that type
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 存在多个过滤器时，用来排序，数字越小越先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否进行拦截，返回true是，false否，可以在此方法里设置一些规则过滤一些请求不用被拦截
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        LOG.info("send {} request to{}", request.getMethod(), request.getRequestURL().toString());

        Object token = request.getParameter("token");
        if (token == null) {
            LOG.warn("access token is empty");
            ctx.setSendZuulResponse(false); // 设置不访问应用
            ctx.setResponseStatusCode(401);
            return null;
        }

        LOG.info("access token ok");
        return null;
    }
}
